<template>
  <div style="display: flex;height: 85vh;">
    <div class="solveName-box">
      <el-table :row-class-name="rowStyle" border @row-click="handleClick" highlight-current-row :data="solveNameList"
        :header-cell-style="{
  background: '#ebebeb'
}">
        <el-table-column label="序号" align="center" type="index" />
        <af-table-column label="解读表格类型名称" align="center" prop="name" />
      </el-table>

    </div>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
        <el-form-item prop="keyName">
          <el-input v-model="queryParams.keyName" placeholder="taxID/Genus/GenusChinese/Species/SpeciesChinese"
            clearable style="width: 360px" @keyup.enter.native="handleQuery" />
        </el-form-item>

        <el-form-item label="状态" prop="contentStatus" style="margin-left: -30px">
          <el-select v-model="queryParams.contentStatus" placeholder="全部" clearable style="width: 240px">
            <el-option value="" label="全部"></el-option>
            <el-option v-for="item in statusType" :key="item.contentStatus" :label="item.title"
              :value="item.contentStatus" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:dict:add']">
            新增
          </el-button>

        </el-col>
        <el-col :span="1.5">
          <el-dropdown trigger="click">
            <el-button type="primary" size="mini">
              导出<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="handleExport('now')">导出当前</el-dropdown-item>
              <el-dropdown-item @click.native="handleExport('all')">导出全部</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-row>


      <el-table ref="multipleTable" :row-class-name="rowStyle" border v-loading="loading" highlight-current-row
        :data="solveDictionaryList" height="calc(100vh - 250px)" @selection-change="handleSelectionChange"
        :header-cell-style="{
  background: '#ebebeb'
}">
        <el-table-column type="selection" width="55" align="center" />
        <af-table-column label="序号" align="center" type="index" width="55" />

        <el-table-column v-for="(item, index) in solveDictionaryList[0].headList" :key="index" :label="item"
          align="center" min-width="150">
          <template slot-scope="{row}">{{ row.contentList && row.contentList[item] }}</template>
        </el-table-column>

        <el-table-column label="状态" fixed="right" align="center" prop="contentStatus" width="120">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.contentStatus == 1" active-color="#169bd5" inactive-color="#aaaaaa"
              @change="switchShowStatus(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="200">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['system:dict:edit']">编辑</el-button>
            <el-button v-if="scope.row.contentStatus === 0" size="mini" style="color: #FA5555;" type="text"
              icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:dict:remove']">删除</el-button>
            <el-button v-else size="mini" style="color: #999999;" type="text" icon="el-icon-delete" disabled>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div>
        <pagination style="margin:0;padding: 0;" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />
      </div>

      <!-- 添加或修改参数配置对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="140px">
          <el-form-item v-for="(el, index) in solveDictionaryList[0].headList" :label="el" :key="index" :prop="el"
            :rules="[{ required: true, message: '内容不能为空' }]">
            <el-input style="width:210px" v-model="form[el]">
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>

        </div>
      </el-dialog>

    </div>
  </div>

</template>

<script>
import { solveDictionary, solveDictionaryUpdate, solveDictionaryEdit, solveDictionaryAdd, solveDictionaryDel, solveName, solveDictionaryUpdateStatus } from "@/api/dictionary/interpretationDictionary/solveDictionary"

export default {
  name: "solveDictionary",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 字典表格数据
      solveDictionaryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        keyName: undefined,
        contentStatus: '',
        dictMicrobialTableId: 1
      },
      statusType: [
        {
          title: '开启',
          contentStatus: 1
        },
        {
          title: '禁用',
          contentStatus: 0
        }
      ],
      // 表单参数
      form: {},
      solveNameList: [],
      editData: [],
      sortNum: '',
      sort: ''
    }
  },

  mounted() {
    this.getNameList()
    this.getList()

  },
  methods: {

    /** 查询微生物列表 */
    getList() {
      this.loading = true
      solveDictionary(this.queryParams).then(response => {
        if (response.rows.length === 0) {
          this.solveDictionaryList[0].headList = ['暂无数据']
        } else {
          this.solveDictionaryList = response.rows
          this.total = response.total
        }
        this.loading = false
      }
      )
      
    },
    getNameList() {
      solveName().then(response => {
        this.solveNameList = response.rows
        this.loading = false
      })
    },
    handleClick(row) {
      this.queryParams.dictMicrobialTableId = row.id
      this.form.dictMicrobialTableId = row.id
      this.solveDictionary = []
      this.getList()
    },
    // 取消按钮
    cancel() {
      this.open = false
      // this.reset()
      this.getList()
    },
    // 表单重置
    reset() {
      this.form = {
        // dictId: undefined,
        // dictName: undefined,
        // dictType: undefined,
        // status: "0",
        // remark: undefined
      }

      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      // this.reset()
      this.form = {}
      this.open = true
      this.title = "微生物解读字典：新增"
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.sortNum = row.sortNum
      this.sort = row.sort
      this.form = row.contentList
      // console.log(this.form);
      this.open = true
      this.title = "微生物解读字典：编辑"
      console.log(row, 11)




      // this.reset()
      // const id = row.id || this.ids
      // solveDictionaryEdit(id).then(response => {

      // })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {

          // console.log(this.form);
          // console.log(data);
          // return
          if (this.title === "微生物解读字典：编辑") {
            // console.log(this.form,777);
            for (let k in this.form) {
              this.editData.push({ content: this.form[k], name: k, dictMicrobialTableId: this.queryParams.dictMicrobialTableId, sortNum: this.sortNum, sort: this.sort })
            }
            console.log(this.editData, 1234);
            // this.form=this.editData
            solveDictionaryUpdate(this.editData).then(response => {
              this.msgSuccess("修改成功")
              this.open = false
              this.getList()
              this.editData = []
            })
          } else {
            let data = []
            for (let k in this.form) {
              data.push({ content: this.form[k], name: k, dictMicrobialTableId: this.queryParams.dictMicrobialTableId })
            }
            solveDictionaryAdd(data).then(response => {
              this.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(row);
      // const id = row.id || this.ids
      let sorts = []
      sorts[0] = row.sort
      console.log(sorts)
      this.$confirm('是否确认删除选中的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return solveDictionaryDel(sorts)
      }).then(() => {
        this.getList()
        this.msgSuccess("删除成功")
      })
    },
    // /** 导出按钮操作 */
    handleExport(e) {
      var different = ''
      var params = ''
      if (e === 'now') {
        different = '当前'
        params = this.queryParams //对应接口参数
      } else if (e === 'all') {
        different = '所有'
        params = null
      } else {
        return
      }
      let that = this
      let loading
      this.$confirm('是否确认导出' + different + '数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        // loading = that.$loading({
        //   lock: true,
        //   text: '导出中',
        //   spinner: 'el-icon-loading',
        //   background: 'rgba(0, 0, 0, 0.7)'
        // })
        solveDictionary(params).then((response) => {
          var headList = response.rows[0].headList
          var test = response.rows.map((it, j) => {
            return headList.map((el, i) => {
              return it.contentList[el]
            })
          })
          response.rows[0].headList.unshift('序号')


          let mydata = [
            response.rows[0].headList,
            ...test.map((item, index) => ([
              index + 1,
              ...test[index]
            ]))

            //[]
            // headList:[1,2,3,4,5]
            // contentList:[{a:2,b:2}]
            // ...row.map((item, index) => (

            //     [
            //       index+1,



            //       // item.contentList[item.headList[0]],
            //       // item.contentList[item.headList[1]],
            //       // item.contentList[item.headList[2]],
            //       // item.contentList[item.headList[3]],
            //       // item.contentList[item.headList[4]],
            //       // item.contentList[item.headList[5]],
            //       // item.contentList[item.headList[6]],
            //       // item.contentList[item.headList[7]],
            //       // item.contentList[item.headList[8]],
            //       // item.contentList[item.headList[9]],
            //       // item.contentList[item.headList[10]],
            //       // item.contentList[item.headList[11]],
            //       // item.contentList[item.headList[12]],
            //       // item.contentList[item.headList[13]],
            //       // item.contentList[item.headList[14]],
            //       // item.contentList[item.headList[15]],
            //     ]
            // ))

          ]
          let requireMerge = []
          that.$util.createxlsx({
            mydata,
            fileName: '微生物解读字典',
            dataList: response.rows,
            type: 'orderId',
            requireMerge,
            loading
          })
        })
      }).catch(function () { })
    },
    //切换状态
    switchShowStatus(row) {
      if (row.contentStatus === 1) {
        this.handleUnPublish(row)
      } else if (row.contentStatus === 0) {
        this.handlePublish(row)
      }
    },
    handlePublish(row) {
      this.$confirm('是否开启', "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return solveDictionaryUpdateStatus({
          ...row,
          contentStatus: 1
        })
      }).then(() => {
        this.getList()
        this.msgSuccess("开启成功")
      }).catch(function () {
      })
    },


    handleUnPublish(row) {
      this.$confirm('是否禁用', "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return solveDictionaryUpdateStatus({
          ...row,
          contentStatus: 0
        })
      }).then(() => {
        this.getList()
        this.msgSuccess("禁用成功")
      }).catch(function () {
      })
    },

    rowStyle({ row }) {
      var arr = this.ids
      for (let i = 0; i < arr.length; i++) {
        if (row.id === arr[i]) {
          return "rowStyle"
        }
      }
    },
  },
  updated() {
    this.$nextTick(() => {
      this.$refs["multipleTable"].doLayout();
    })

  },
}
</script>
<style scoped>
/* //解决固定列距表格的高度（注意：这里我写死了表头为一行文字时的高度） */
.el-table__fixed-body-wrapper {
  top: 48px !important;
}

/* //解决多出来的横线(固定列右边)问题 */
.el-table__fixed-right {
  height: 100% !important;
  /* //设置高优先，以覆盖内联样式 */
}

/* //若左右都有固定列时 */
.el-table__fixed {
  height: 100% !important;
  /* //设置高优先，以覆盖内联样式 */
}


.solveName-box {
  width: 30%;
  padding: 20px;
  height: 100%;
  border-right: 1px solid #dfe6ec;
}

.app-container {
  width: 70%;
  height: 100%;
}

.b {
  width: 31% !important;
}

::v-deep .el-table__body tr.current-row>td {

  background: #a8d6fe !important;
}

::v-deep .rowStyle {
  background-color: #a8d6fe !important;
}

::v-deep .el-table__body tr:hover>td {
  background: #a8d6fe !important;
}
</style>
